package com.api.demo.config;

import java.io.File;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.api.demo.filter.RequestCachingFilter;
import com.api.demo.interceptor.ApiLogInterceptor;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Resource
    private ApiLogInterceptor apiLogInterceptor;

    @Autowired
    private FileStorageConfig fileStorageConfig;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(apiLogInterceptor)
                .addPathPatterns("/api/**")
                .excludePathPatterns("/static/**", "/error");
    }

    @Bean
    public FilterRegistrationBean<RequestCachingFilter> requestCachingFilter() {
        FilterRegistrationBean<RequestCachingFilter> bean = new FilterRegistrationBean<>(new RequestCachingFilter());
        bean.addUrlPatterns("/*");
        return bean;
    }


    
    @PostConstruct
    public void init() {
        // 确保上传目录存在
        File uploadDir = new File(fileStorageConfig.getUploadDir());
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置静态资源映射，使上传的文件可以通过URL访问
        registry.addResourceHandler(fileStorageConfig.getUrlPrefix() + "**")
                .addResourceLocations("file:" + fileStorageConfig.getUploadDir() + "/");
    }
} 
